/**
* pdaScan 处理PDA扫码逻辑和调用相机扫码功能
*/

import {
	onMounted,
	onUnmounted,
} from 'vue'
import permision from "@/common/permission.js"
export default function() {
	onUnmounted(() => {
		// 移除监听事件
		console.log('移除监听PDA扫码事件')
		uni.$off('scancodedate')
	})
	const scan = async () => {
		// #ifdef APP-PLUS
		let status = await checkPermission();
		if (status !== 1) {
			return;
		}
		// #endif
		return new Promise((resolve, reject) => {
			uni.scanCode({
				success: (res) => {
					// 输出扫码值
					resolve(res.result)
				},
				fail: (err) => {
					// 需要注意的是小程序扫码不需要申请相机权限
					reject(false)
				}
			});
		})
	}
	// #ifdef APP-PLUS
	// 检测相机权限
	const checkPermission = async (code) => {
		let status = permision.isIOS ? await permision.requestIOS('camera') :
			await permision.requestAndroid('android.permission.CAMERA');

		if (status === null || status === 1) {
			status = 1;
		} else {
			uni.showModal({
				content: "需要相机权限",
				confirmText: "设置",
				success: function(res) {
					if (res.confirm) {
						permision.gotoAppSetting();
					}
				}
			})
		}
		return status;
	}
	// #endif
	return {
		scan
	}
}
